$(function () {
//定义全局变量
    window.pageSize = 5;
    window.pageNum = 1;
    window.keyword = "";
    //在全局作用域内创建advertiseIdArray
    window.advertiseIdArray = new Array();

    showPage();
    //查询
    $("#searchBtn").click(function () {
        //获取keyword
        var keyword = $("#keywordInput").val();
        //验证
        // if (keyword.length == 0) {
        //     layer.msg("请填写关键字");
        //     return;
        // }
        //更新全局变量
        window.keyword = keyword;
        //更新数据
        showPage();
    });
    //添加
    $("#addBtn").click(function () {
        $("#advertiseNameInput").val("");
        $("#advertiseIconpathInput").val("");
        $("#advertiseStatusInput").val("");
        $("#advertiseUrlInput").val("");
        $("#advertiseUseridInput").val("");

        $("#addModal").modal("show");
    });
    //保存
    $("#addModalBtn").click(function () {
        // 1.收集文本框内容
        var advertiseName = $.trim($("#advertiseNameInput").val());
        var advertiseIconpath = $.trim($("#advertiseIconpathInput").val());
        var advertiseStatus = $.trim($("#advertiseStatusInput").val());
        var advertiseUrl = $.trim($("#advertiseUrlInput").val());
        var advertiseUserid = $.trim($("#advertiseUseridInput").val());
        if (advertiseName.length==0) {
            layer.msg("名称不能为空");
            return;
        }
        if (advertiseIconpath.length==0) {
            layer.msg("图标路径不能为空");
            return;
        }
        if (advertiseStatus.length==0) {
            layer.msg("状态不能为空");
            return;
        }
        if (advertiseUrl.length==0) {
            layer.msg("路径不能为空");
            return;
        }
        if (advertiseUserid.length==0) {
            layer.msg("用户ID不能为空");
            return;
        }
        $.ajax({
            url: "/advertise/save/advertise",
            type: "post",
            data: {
                "name": advertiseName,
                "iconpath":advertiseIconpath,
                "status":advertiseStatus,
                "url":advertiseUrl,
                "userid":advertiseUserid
            },
            dataType: "json",
            success: function (ajaxResult) {
                var result = ajaxResult.result;
                if (result == "SUCCESS") {
                    showPage();
                    layer.msg("添加成功")
                } else {
                    layer.msg("添加失败");
                }
                $("#addModal").modal("hide");
            }
        });
    });
    //删除
    $("#batchRemoveBtn").click(function () {
        // 获取选中的advertiseid
        var length = $(".itemBox:checked").length;
        // 判断是否有数据
        if (length == 0) {
            layer.msg("请至少选择一行数据！");
            return;
        }
        $(".itemBox:checked").each(function () {
            var advertiseid = $(this).attr("advertiseid");
            window.advertiseIdArray.push(advertiseid);
        });
        // 调用函数打开模态框
        showRemoveConfirmModal();
    });
    //单条删除
    $("#advertiseTableBody").on('click', '.removeBtn', function () {
        var advertiseid = $(this).attr("advertiseid");
        window.advertiseIdArray.push(advertiseid);
        //打开模态框
        showRemoveConfirmModal();

    })
    //确认删除
    $("#confirmModalBtn").click(function () {
        var requestBody = JSON.stringify(window.advertiseIdArray);
        $.ajax({
            url: "/advertise/batch/remove",
            type: "post",
            data: requestBody,
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            success: function (ajaxResult) {

                if (ajaxResult.result == "SUCCESS") {
                    // 如果删除成功，则重新调用分页方法
                    showPage();
                    layer.msg("删除成功")
                } else {
                    layer.msg("删除失败")
                }
                // 不管成功还是失败，都需要关掉模态框
                $("#advertiseConfirmModal").modal("hide");
            },
        });
    });
    //修改
    $("#advertiseTableBody").on("click",".editBtn",function(){
        // 1.获取当前按钮的advertiseId
        window.advertiseId = $(this).attr("advertiseid");
        // 2.调用方法,回显到文本框
        updateSelectAdvertise();
        // 4.打开模态框
        $("#editModal").modal("show");
        showPage();
    });
    //确认修改
    $("#editModalBtn").click(function () {
        // 1.获取文本框值
        var advertiseName = $("#advertiseNameInputEdit").val();
        var advertiseIconpath = $("#advertiseIconpathInputEdit").val();
        var advertiseStatus = $("#advertiseStatusInputEdit").val();
        var advertiseUrl = $("#advertiseUrlInputEdit").val();
        var advertiseUserid = $("#advertiseUseridInputEdit").val();
        if(advertiseName.length==0) {
            layer.msg("不能为空！");
            return ;
        }
        if(advertiseIconpath.length==0) {
            layer.msg("不能为空！");
            return ;
        }if(advertiseStatus.length==0) {
            layer.msg("不能为空！");
            return ;
        }if(advertiseUrl.length==0) {
            layer.msg("不能为空！");
            return ;
        }if(advertiseUserid.length==0) {
            layer.msg("不能为空！");
            return ;
        }
        $.ajax({
            url:"/advertise/update/advertise",
            type:"post",
            data:{
                "id":window.advertiseId,
                "name":advertiseName,
                "iconpath":advertiseIconpath,
                "status":advertiseStatus,
                "url":advertiseUrl,
                "userid":advertiseUserid
            },
            dataType:"json",
            success:function (ajaxResult) {
                if(ajaxResult.result == "SUCCESS") {
                    // 3.操作成功重新分页
                    layer.msg("修改成功")
                }else{
                    layer.msg("修改失败");
                }
                showPage();
                // 4.不管成功还是失败，关闭模态框
                $("#editModal").modal("hide");
            }
        });
    });
    // 全选/全不选功能
    $("#summaryBox").click(function () {
        // 1.获取当前checkbox的选中状态
        var currentStatus = this.checked;
        // 2.设置itemBox的选中状态
        $(".itemBox").prop("checked", currentStatus);

    });
});
//跟据id查询修改
function updateSelectAdvertise() {
    $.ajax({
        url:"/advertise/update/select",
        type:"post",
        dataType:"json",
        data:{
            "id":window.advertiseId
        },
        success:function (ajaxResult) {
            if(ajaxResult.result == "SUCCESS"){
                //清空旧数据
                $("#advertiseTableBody").empty();
                var data  = ajaxResult.data;
                var advertiseName = data.name;
                var advertiseIconpath = data.iconpath;
                var advertiseStatus =data.status;
                var advertiseUrl = data.url;
                var advertiseUserid = data.userid;
                $("#advertiseNameInputEdit").val(advertiseName);
                $("#advertiseIconpathInputEdit").val(advertiseIconpath);
                $("#advertiseStatusInputEdit").val(advertiseStatus);
                $("#advertiseUrlInputEdit").val(advertiseUrl);
                $("#advertiseUseridInputEdit").val(advertiseUserid);
            }else{
                layer.msg("查询更新数据失败！")
            }
        }
    });
}
//打开删除的模态框
function showRemoveConfirmModal() {
    $("#advertiseConfirmModal").modal("show");
    var requestBody = JSON.stringify(window.advertiseIdArray);
    $.ajax({
        url: "/advertise/get/list/by/id/list",
        type: "post",
        data: requestBody,
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        success: function (ajaxResult) {
            if (ajaxResult.result == "SUCCESS") {
                $('#confirmModalTableBody').empty();
                //渲染数据
                var list = ajaxResult.data;
                for (var i = 0; i < list.length; i++) {
                    var tr = $('<tr></tr>');
                    var td1 = $('<td>' + (i + 1) + '</td>');
                    var td2 = $('<td>' + list[i].name + '</td>');
                    var td3 = $('<td>' + list[i].iconpath + '</td>');
                    var td4 = $('<td>' + list[i].status + '</td>');
                    var td5 = $('<td>' + list[i].url + '</td>');
                    var td6 = $('<td>' + list[i].userid + '</td>');

                    tr.append(td1);
                    tr.append(td2);
                    tr.append(td3);
                    tr.append(td4);
                    tr.append(td5);
                    tr.append(td6);
                    $("#confirmModalTableBody").append(tr);
                }
            } else {
                layer.msg("删除数据失败！");
            }
        }
    })
}
//显示分页数据
function showPage() {
    $.ajax({
        url: "/advertise/search/by/keyword",
        type: "post",
        data: {
            "pageNum": window.pageNum,
            "pageSize": window.pageSize,
            "keyword": window.keyword
        },
        dataType: "json",
        success: function (ajaxResult) {
            if (ajaxResult.result == "SUCCESS") {
                var list = ajaxResult.data.list;
                //清空旧数据
                $("#advertiseTableBody").empty();
                if (list.length == 0) {
                    //没数据
                    var tr = $('<tr></tr>');
                    var td = $('<td colspan="4">没有查询到数据！</td>');
                    tr.append(td);
                    $("#advertiseTableBody").append(tr);
                } else {
                    //有数据
                    for (var i = 0; i < list.length; i++) {
                        var tr = $('<tr></tr>');
                        var td1 = $('<td>' + (i + 1) + '</td>');
                        var td2 = $('<td><input advertiseid="' + list[i].id + '" class="itemBox" type="checkbox"></td>');
                        var td3 = $('<td>' + list[i].name + '</td>');
                        var td4 = $('<td>' + list[i].iconpath + '</td>');
                        var td5 = $('<td>' + list[i].status + '</td>');
                        var td6 = $('<td>' + list[i].url + '</td>');
                        var td7 = $('<td>' + list[i].userid + '</td>');
                        var td8 = $('<td></td>');
                        var btn1 = $('<button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button>');
                        var btn2 = $('<button advertiseid="' + list[i].id + '" type="button" class="btn btn-primary btn-xs editBtn"><i class=" glyphicon glyphicon-pencil"></i></button>');
                        var btn3 = $('<button advertiseid="' + list[i].id + '" type="button" class="btn btn-danger btn-xs removeBtn"><i class=" glyphicon  glyphicon-remove"></i></button>');
                        td8.append(btn1);
                        td8.append(btn2);
                        td8.append(btn3);

                        tr.append(td1);
                        tr.append(td2);
                        tr.append(td3);
                        tr.append(td4);
                        tr.append(td5);
                        tr.append(td6);
                        tr.append(td7);
                        tr.append(td8);
                        $('#advertiseTableBody').append(tr);
                    }

                    initPagination(ajaxResult.data);
                }
            }
        }
    });
};
// 声明函数封装导航条初始化操作
function initPagination(pageInfo) {
    // 声明变量存储总记录数
    var totalRecord = pageInfo.total;
    // 声明变量存储分页导航条显示时的属性设置
    var paginationProperties = {
        num_edge_entries: 3,        //边缘页数
        num_display_entries: 5,      //主体页数
        callback: pageselectCallback, //回调函数
        items_per_page: window.pageSize,    //每页显示数据数量，就是pageSize
        current_page: (window.pageNum - 1),//当前页页码
        prev_text: "上一页",       //上一页文本
        next_text: "下一页"        //下一页文本
    };
    // 显示分页导航条
    $("#Pagination").pagination(pageInfo.total, paginationProperties);
}

// 在每一次点击“上一页”、“下一页”、“页码”时执行这个函数跳转页面
function pageselectCallback(pageIndex, jq) {
    // pageIndex从0开始，pageNum从1开始
    window.pageNum = pageIndex + 1;
    var keyword = window.keyword;
    // 跳转页面
    showPage();
    return false;
}